package com.example.qt.ptplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.qt.ptplatform.entity.*;
import com.example.qt.ptplatform.mapper.CommentFavoriteMapper;
import com.example.qt.ptplatform.mapper.CommentImageMapper;
import com.example.qt.ptplatform.mapper.CommentLikeMapper;
import com.example.qt.ptplatform.mapper.CommentMapper;
import com.example.qt.ptplatform.service.CommentService;
import com.example.qt.ptplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Autowired
    private CommentFavoriteMapper commentFavoriteMapper;

    @Override
    public Integer saveComment(Integer torrentId, Integer userId, String content, Boolean isAnonymous) {
        Comments comment = new Comments();
        comment.setTorrentId(torrentId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setIsAnonymous(isAnonymous);
        comment.setCommentTime(new Date());
        commentMapper.insert(comment);
        // 返回插入后生成的commentId
        return comment.getCommentId();
    }

    @Override
    public Integer saveReply(Integer torrentId, Integer userId, String content, Boolean isAnonymous, Integer comCommentId) {
        Comments reply = new Comments();
        reply.setTorrentId(torrentId);
        reply.setUserId(userId);
        reply.setContent(content);
        reply.setIsAnonymous(isAnonymous);
        reply.setComCommentId(comCommentId);
        reply.setCommentTime(new Date());
        commentMapper.insert(reply);

        Comments originalComment = commentMapper.selectById(comCommentId);
        if (originalComment != null) {
            originalComment.setReplyCount(originalComment.getReplyCount() + 1);
            commentMapper.updateById(originalComment);
        }

        // 返回新生成的回复ID
        return reply.getCommentId();
    }

    @Override
    @Transactional
    public void likeComment(Integer userId, Integer commentId) {
        // 检查是否已点赞
        if (commentLikeMapper.existsByUserAndComment(userId, commentId) > 0) {
            return;
        }

        // 保存点赞关系
        CommentLike like = new CommentLike();
        like.setUserId(userId);
        like.setCommentId(commentId);
        like.setCreateTime(LocalDateTime.now());
        commentLikeMapper.insert(like);

        // 更新评论点赞数
        Comments comment = commentMapper.selectById(commentId);
        if (comment != null) {
            comment.setLikesCount(comment.getLikesCount() + 1);
            commentMapper.updateById(comment);
        }
    }

    @Override
    @Transactional
    public void unlikeComment(Integer userId, Integer commentId) {
        // 删除点赞关系
        QueryWrapper<CommentLike> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("comment_id", commentId);
        commentLikeMapper.delete(wrapper);

        // 更新评论点赞数
        Comments comment = commentMapper.selectById(commentId);
        if (comment != null && comment.getLikesCount() > 0) {
            comment.setLikesCount(comment.getLikesCount() - 1);
            commentMapper.updateById(comment);
        }
    }

    @Override
    public boolean checkLikeStatus(Integer userId, Integer commentId) {
        return commentLikeMapper.existsByUserAndComment(userId, commentId) > 0;
    }

    @Override
    @Transactional
    public void deleteComment(Integer commentId) {
        // 先删除子评论
        deleteChildComments(commentId);

        // 删除点赞记录
        QueryWrapper<CommentLike> likeWrapper = new QueryWrapper<>();
        likeWrapper.eq("comment_id", commentId);
        commentLikeMapper.delete(likeWrapper);

        // 删除收藏记录
        QueryWrapper<CommentFavorite> favoriteWrapper = new QueryWrapper<>();
        favoriteWrapper.eq("comment_id", commentId);
        commentFavoriteMapper.delete(favoriteWrapper);

        //删除评论关联的图片（新增）
        QueryWrapper<CommentImage> imageWrapper = new QueryWrapper<>();
        imageWrapper.eq("comment_id", commentId);
        commentImageMapper.delete(imageWrapper);

        // 获取当前评论
        Comments comment = commentMapper.selectById(commentId);
        if (comment != null) {
            // 如果是回复，更新父评论的回复数
            if (comment.getComCommentId() != null) {
                Comments parentComment = commentMapper.selectById(comment.getComCommentId());
                if (parentComment != null) {
                    parentComment.setReplyCount(parentComment.getReplyCount() - 1);
                    commentMapper.updateById(parentComment);
                }
            }
            // 最后删除评论本身
            commentMapper.deleteById(commentId);
        }
    }

    /**
     * 递归删除所有子评论
     */
    private void deleteChildComments(Integer parentCommentId) {
        // 查询所有子评论
        List<Comments> childComments = commentMapper.selectList(
                new QueryWrapper<Comments>().eq("com_comment_id", parentCommentId)
        );

        if (childComments != null && !childComments.isEmpty()) {
            // 递归删除每个子评论的子评论
            for (Comments childComment : childComments) {
                deleteChildComments(childComment.getCommentId());
                // 删除当前子评论
                commentMapper.deleteById(childComment.getCommentId());
            }
        }
    }

    @Resource
    private UserService userService;

    @Autowired
    private CommentImageMapper commentImageMapper;

    @Override
    public List<Comments> getCommentsByTorrentId(Integer torrentId) {
        // 1. 查询所有评论
        List<Comments> allComments = commentMapper.selectList(
                new QueryWrapper<Comments>().eq("torrent_id", torrentId)
        );

        if (allComments == null || allComments.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 查询所有评论对应的图片
        List<Integer> commentIds = allComments.stream()
                .map(Comments::getCommentId)
                .collect(Collectors.toList());

        Map<Integer, List<String>> commentImagesMap = new HashMap<>();
        if (!commentIds.isEmpty()) {
            List<CommentImage> images = commentImageMapper.selectList(
                    new QueryWrapper<CommentImage>()
                            .in("comment_id", commentIds)
            );

            images.forEach(img -> {
                commentImagesMap.computeIfAbsent(img.getCommentId(), k -> new ArrayList<>())
                        .add(img.getImageData());
            });
        }

        // 3. 构建评论树结构并设置用户名和图片
        Map<Integer, Comments> commentMap = new HashMap<>();
        allComments.forEach(item -> {
            // 设置用户名
            User user = userService.getById(item.getUserId());
            if (user != null && user.getUserId() != null) {
                item.setUserName(user.getUsername());
            }

            // 设置评论图片
            item.setImages(commentImagesMap.getOrDefault(item.getCommentId(), Collections.emptyList()));

            commentMap.put(item.getCommentId(), item);
        });

        List<Comments> treeComments = new ArrayList<>();
        for (Comments comment : allComments) {
            if (comment.getComCommentId() == null) {
                treeComments.add(comment);
            } else {
                Comments parent = commentMap.get(comment.getComCommentId());
                if (parent != null) {
                    if (parent.getReplies() == null) {
                        parent.setReplies(new ArrayList<>());
                    }
                    parent.getReplies().add(comment);
                }
            }
        }

        return treeComments;
    }

}